package com.sunriz.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunriz.domain.AjaxResult;
import com.sunriz.domain.SpaResult;
import com.sunriz.service.CtrlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: 童锣烧
 * @time: 2023/11/09
 */
@RestController
@RequestMapping("/iot")
public class CtrlController {

    @Autowired
    private CtrlService ctrlService;

    /**
     * 查找hc控制器中地理纬度、地理经度、海拔高度、年平均压力、年平均温度的值
     * @return
     */
    @GetMapping("/get")
    public List<SpaResult> testReport(){
        List<SpaResult> result=ctrlService.select();
        return result;
    }

    /**
     * 数据下发接口
     */
    @PostMapping("/api/wot/{tdCode}/{deviceCode}/properties/")
    public AjaxResult testSend(@PathVariable String tdCode, @PathVariable String deviceCode, @RequestBody String param){
        JSONObject inputObject= JSON.parseObject(param);

        String mcDeviceCode = "\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b";
        String ccDeviceCode="\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}_\\d{1}\\b";
        String hcDeviceCode="\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}_\\d{1}_\\d{1}\\b";

        Pattern pattern =null;
        Matcher matcher=null;

        //输入值健壮性分析
        switch(tdCode){
            case("mc"):
                pattern = Pattern.compile(mcDeviceCode);
                matcher = pattern.matcher(deviceCode);
                if (!matcher.matches())
                    return AjaxResult.error(false,null,null,"mc与deviceCode不匹配");
                break;
            case("cc"):
                pattern = Pattern.compile(ccDeviceCode);
                matcher = pattern.matcher(deviceCode);
                if (!matcher.matches())
                    return AjaxResult.error(false,null,null,"cc与deviceCode不匹配");
                break;
            case("hc"):
                pattern = Pattern.compile(hcDeviceCode);
                matcher = pattern.matcher(deviceCode);
                if (!matcher.matches())
                    return AjaxResult.error(false,null,null,"hc与deviceCode不匹配");
                break;
            default:
                return AjaxResult.error(false,null,null,"tdCode输入有误");
        }

        JSONObject dataObject=ctrlService.update(tdCode,deviceCode,param);
        return AjaxResult.success(true,dataObject,null,null);
    }

    /**
     * 定时运行SPA算法
     */
    @Scheduled(cron="0/20 * * * * *")
    public void runSPA()  throws Exception{
        double start = System.currentTimeMillis();
        System.out.println("执行SPA算法");
        ctrlService.runSPA();

    }
}
